#include "DrawGraph.h"

void DrawGraph::Start(int mode)
{
	FILE* fp = fopen(temp_file.c_str(), "w");
	if (mode == DiGraph)
		fprintf(fp, "digraph my_graph{\n");
	else if (mode == Graph)
		fprintf(fp, "graph my_graph{\n");
	fclose(fp);
}

int DrawGraph::Create_Node(std::string node_name)
{
	FILE* fp = fopen(temp_file.c_str(), "a");
	str2int[node_name] = ++node_cnt;
	int2str[node_cnt] = node_name;

	fprintf(fp, "\t%s;\n", node_name.c_str());

	fclose(fp);
	return node_cnt;
}

int DrawGraph::Create_Node(int node_name)
{
	std::string str_node_name = std::to_string(node_name);
	return Create_Node(str_node_name);
}

int DrawGraph::Find_Node(std::string node_name)
{
	if (str2int.find(node_name) == str2int.end())
		return -1;
	return str2int[node_name];
}

std::string DrawGraph::Find_Node(int node_id)
{
	if (node_id > node_cnt || node_id <= 0)
		return std::string();
	return int2str[node_id];
}

int DrawGraph::Create_Relationship(std::string start_name, std::string end_name, int mode, std::string label)
{
	FILE* fp = fopen(temp_file.c_str(), "a");

	fprintf(fp, "\t%s ", start_name.c_str());

	if (mode == DiGraph) {
		fprintf(fp, " -> ");
	}
	else if (mode == Graph) {
		fprintf(fp, " -- ");
	}

	fprintf(fp, " %s ", end_name.c_str());

	if (label != std::string("")) {
		fprintf(fp, "[label=%s]", label.c_str());
	}

	fprintf(fp, ";\n");

	fclose(fp);
	return ++rela_cnt;
}

int DrawGraph::Create_Relationship(int start_id, int end_id, int mode, std::string label)
{
	if (Find_Node(start_id) == std::string() || Find_Node(end_id) == std::string())
		return -1;
	return Create_Relationship(Find_Node(start_id), Find_Node(end_id), mode, label);
}

void DrawGraph::End()
{
	FILE* fp = fopen(temp_file.c_str(), "a");

	fprintf(fp, "}");

	fclose(fp);
}

void DrawGraph::Print_Dot(std::string file_path)
{
	std::ifstream in(temp_file.c_str());
	std::ofstream out(file_path.c_str());
	out << in.rdbuf();
	in.close();
	out.close();
}

void DrawGraph::Get_Png(std::string file_path)
{
	std::string command = "dot -Tpng " + temp_file + " -o " + file_path;
	system(command.c_str());
}
